import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue';

export function useTableHeight(options = {}) {
	const { tableRef: externalTableRef = null, hasPagination = true } = options;

	const internalTableRef = ref(null);
	const tableRef = externalTableRef || internalTableRef;
	const maxHeight = ref(0);

	let resizeObserver = null;

	const calculateTableHeight = () => {
		if (!tableRef.value || !tableRef.value.$el) return;
		const windowHeight = window.innerHeight;
		const tableTop = tableRef.value.$el.getBoundingClientRect().top + 30;
		const bottomPadding = hasPagination ? 30 : 20;
		return windowHeight - tableTop - bottomPadding;
	};

	const setTableHeight = () => {
		nextTick(() => {
			requestAnimationFrame(() => {
				maxHeight.value = calculateTableHeight();
				console.log(maxHeight.value);
			});
		});
	};

	onMounted(() => {
		setTimeout(() => {
			setTableHeight();
		}, 100); // 延迟初始化

		window.addEventListener('resize', setTableHeight);

		if (tableRef.value && tableRef.value.$el) {
			resizeObserver = new ResizeObserver(() => {
				setTableHeight();
			});
			resizeObserver.observe(tableRef.value.$el);
		}
	});

	onUnmounted(() => {
		window.removeEventListener('resize', setTableHeight);
		if (resizeObserver) {
			resizeObserver.disconnect();
		}
	});

	watch(
		() => tableRef.value,
		(newVal) => {
			if (newVal && newVal.$el) {
				setTableHeight();
			}
		},
		{ immediate: true },
	);

	const updateTableHeight = () => {
		nextTick(setTableHeight);
	};

	return {
		tableRef,
		maxHeight,
		setTableHeight,
		updateTableHeight,
	};
}
